﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace ServBus.ListForm2010.Utility
{
    public class CreateFieldLogic
    {
        private TypeFile mTypeFile;
        private Schema mSchema;
        private Manifest mManifest;
        private Sampledata mSampleData;
        private View mView;
        private List<ListInfo> mListInfos;
        private string mPath;
        private InfoPathContext mContext;
        private ListInfo mListInfo;
        private TypeControl mTypeControlFile;
        private Template mTemplate;

        public CreateFieldLogic(ListInfo listInfo, InfoPathContext context)
        {
            mListInfo = listInfo;
            mContext = context;

            mTypeControlFile = new TypeControl(mContext);
            mTypeFile = new TypeFile(mContext);
            mSampleData = new Sampledata(mContext);
            mView = new View(mContext);
            mPath = mContext.Path;
            Directory.CreateDirectory(mContext.Path);
            mSchema = new Schema(mContext);
            mTemplate = new Template(mContext);
            mListInfos = listInfo.LookupLists;
            mManifest = new Manifest(mContext);
        }

        public void BeginToCreate()
        {
            CreateManifest();
            CreateSampleData();
            CreateTypeFile();

            CreateBuildInControlFile();
            CreateSchema();
            CreateTemplateFile();

            CreateTypeFile();
            CreateViewFile();
            CreateCab();
        }

        private void CreateManifestOld()
        {
            string path = "manifest.xsf";
            mManifest.CreateTemplateManifest();
            mContext.AddSavedFile(path);
        }

        private void CreateManifest()
        {
            string path = "manifest.xsf";
            mManifest.CreateTemplateManifest();
            AddExtensionInManifest();
            // CreateContentTypes();
            mManifest.AddXmlToEdit();
            //mManifest.AddQueryObject();
            mContext.AddSavedFile(path);
        }


        private void CreateBuildInControlFile()
        {
            mTypeControlFile.CreateTypeControlsFile();
            string path = "builtincontrolsschema.xsd";
            mContext.AddSavedFile(path);
        }

        private void CreateSampleData()
        {
            mSampleData.CreateBasicSample();
            mSampleData.AddDefaultValue();
            string path = "sampledata.xml";
            mContext.AddSavedFile(path);
        }

        private void CreateSchema()
        {
            //添加主表Field结构到MySchema文件
            mSchema.AddRootListElement(mListInfo, false);
            try
            {
                if (mListInfos.Count != 0)
                {
                    //添加SubForms引用到主表Field结构中
                    mSchema.AddListFieldsRefInMyFields("SubForms", false);
                    //添加SubForms结构框架
                    mSchema.AddElementToRoot("SubForms");
                }

                int count = 1;
                foreach (ListInfo listInfo in mListInfos)
                {
                    //添加子表结构框架，与MyFields
                    mSchema.AddListElementToRoot("List" + count, listInfo.Name, listInfo.ListId);
                    mSchema.AddContentTypeElementToRoot("ContentType" + count, listInfo.CTypeName, listInfo.CTypeId);
                    foreach (FieldInfo fldInfo in listInfo.Fields)
                    {
                        try
                        {
                            //在子表结构的定义里插入子表Fields
                            mSchema.AddListFieldToSchema("ContentType" + count, fldInfo);
                        }
                        catch (Exception e)
                        {
                        }
                    }

                    mSchema.AddListFieldToElement("SubForms", "List" + count, false);
                    mSchema.AddListFieldToElement("List" + count, "ContentType" + count, true);
                    count++;
                }
            }
            catch (Exception ex)
            {
                string exStr = ex.ToString();
            }

            mContext.AddSavedFile("myschema.xsd");
            ClearBlank();
        }

        public void CreateCab()
        {
            CabCreater cab = new CabCreater(mContext);
            cab.Create();
        }

        public void CreateTypeFile()
        {
            mTypeFile.CreateTypeFile();
            mContext.AddSavedFile("typeschema.xsd");
        }

        public void CreateTemplateFile()
        {
            mTemplate.CreateBasicTemplate();
            mTemplate.AddDefaultValue();
            mContext.AddSavedFile("template.xml");
        }

        public void CreateBuildInControl()
        {
            mTypeControlFile.CreateTypeControlsFile();
            mContext.AddSavedFile("builtincontrolsschema.xsd");
        }

        private void CreateViewFile()
        {
            mView.CreateView();
            mContext.AddSavedFile("view1.xsl");
        }

        private void ClearBlank()
        {
            foreach (string path in mContext.FilesToBeCleared)
            {
                string newContent = null;
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
                {
                    StreamReader sr = new StreamReader(fs);
                    newContent = sr.ReadToEnd();
                    newContent = Regex.Replace(newContent, @">\s+</", "></");
                }

                File.WriteAllText(path, newContent);
            }
        }

        //2011-11-17
        private void AddExtensionInManifest()
        {
            // string siteUrl = mContext.CurrentSiteUrl;
            string listName = mContext.ListName;
            // http://msp-dev-server0:4000/sites/site1/Lists/CustomerInfoList/testfld/testflddest.xsn\
            //string siteUrl = mContext.Web.Site.ServerRelativeUrl;
            // /sites/site1/Lists/CustomerInfoList/testFld/CustomerInfoList_UserInfoCt_OrderInfoList_OrderInfoCt.xsn
            //SPList list = mContext.Web.Lists[mContext.ListName];
            //string path = list.RootFolder.ServerRelativeUrl + "/" + NameSpaceConstants.Name_Folder_In_List + "/" + mContext.XsnName + ".xsn";
            //string relativeUrl = siteUrl + "/Lists/" + listName + "/" + NameSpaceConstants.Name_Folder_In_List + "/" + mContext.XsnName + ".xsn";

            //// http://msp-dev-server0:4000/sites/site1/Lists/CustomerInfoList/testFld/wokao.xsn
            //string url = mContext.CurrentSiteUrl + "/Lists/" + listName + "/" + NameSpaceConstants.Name_Folder_In_List + "/" + mContext.XsnName + ".xsn";
            //string fulSiteUrl = mContext.CurrentSiteUrl;
            //Uri requestUri = mContext.PageUrl;
            //string serverUrl = requestUri.Scheme
            //            + Uri.SchemeDelimiter
            //            + requestUri.Host
            //            + (requestUri.IsDefaultPort ? "" : ":"
            //            + requestUri.Port);

            string siteUrl = mContext.CurrentSiteUrl;
            string path = mContext.XsnName + ".xsn";
            string ctNam = "Form_" + mContext.XsnName;
            string fulUrl = mContext.MainListFullUrl + "/" + mContext.ListContentTypeName + "/" + mContext.XsnName + ".xsn";
            mManifest.AddExtensions(siteUrl, path, ctNam, fulUrl);
            // site="/sites/site1" 
            // path="/sites/site1/Lists/CustomerInfoList/testFld/CustomerInfoList_UserInfoCt_OrderInfoList_OrderInfoCt.xsn" 
            // name="CustomerInfoList_UserInfoCt_OrderInfoList_OrderInfoCt"
            // path="http://msp-dev-server0:4000/sites/site1/Lists/CustomerInfoList/testFld/wokao.xsn"
            // site="http://msp-dev-server0:4000/sites/site1"
            // http://msp-dev-server0:4000
        }

        /// <summary>
        /// 创建两个ContentType,一个用于数据交互，一个用于表单
        /// </summary>
        public void CreateContentTypes()
        {
            SPUtility.AddContentTypeInWeb(mContext.ListName, mContext.XsnName, mContext.Web);

            SPUtility.AddSecContentTypeInList(mContext);

        }
    }
}
